<template>
  <div class="pre">
    <el-container class="body">
      <el-header class="bg">
        <el-row :gutter="20" style="margin-left: 10px;">
          <el-col :span="24" style="padding-left: 10px;display: flex;">
            <div class="div-padding">
              合同类型:
              <el-select v-model="s_accountTypeStrList" multiple placeholder="请选择">
                <el-option v-for="item in accountTypeStrList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="div-padding">
              合同编号:
              <el-input v-model="contractNo" class="input-mid" clearable></el-input>
            </div>
            <div class="div-padding">
              逾期天数范围:
              <el-input v-model="d_s" class="input-mini" @input="handleInput"></el-input>
              -
              <el-input v-model="d_e" class="input-mini" @input="handleInput"></el-input>
            </div>
            <div class="div-padding">
              客户状态:
              <el-select v-model="s_customerStatusStrList" multiple placeholder="请选择">
                <el-option v-for="item in customerStatusStrList" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="div-padding">
              排除专营店:
              <el-select v-model="s_excludeDlrSimpleNameList" multiple filterable placeholder="请选择">
                <el-option v-for="item in excludeDlrSimpleNameList" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;margin-left: 10px;">
          <el-col :span="12" style="display: flex;">
            <el-button type="primary" icon="el-icon-search" @click="getPreCase">查询</el-button>
            <el-button type="primary" icon="el-icon-circle-plus-outline" @click="addPreGrabPoolBatch">添加勾选到待抢池</el-button>
            <el-button type="success" plain icon="el-icon-download" :loading="exportLoading"
              @click="exportPreCase">导出查询结果为Excel</el-button>
            <el-upload class="upload" action="http://192.168.10.21:12999/df/api/importGrabCasePool" :limit="1"
              :on-success="importGrabCasePoolSuccess">
              <el-button icon="el-icon-upload" type="warning">导入Excel到待抢池</el-button>
            </el-upload>
          </el-col>
          <el-col :span="12" style="display: flex;justify-content: flex-end;padding-right: 40px;">
            <div style="padding-right: 10px;display: inline-block; ">
              <el-statistic v-if="nextEightThirty" @finish="startGrabCase" :value="nextEightThirty" time-indices
                title="🎉距离抢案还剩🎉">
                <template slot="suffix">
                  抢案即将开始
                </template>
              </el-statistic>
            </div>
            <el-badge :value="preNumber" class="item">
              <el-button type="primary" plain icon="el-icon-s-help"
                @click="preGrabCasePoolTable = true">查看待抢池数据</el-button>
            </el-badge>
          </el-col>
        </el-row>
      </el-header>
      <el-divider></el-divider>
      <el-main class="data ele-scrollbar">
        <div class="tab-data ele-scrollbar">
          <el-table ref="multipleTable" :data="tableData" border stripe v-loading="tableLoading" max-height="600"
            class="ele-scrollbar" :header-cell-class-name="headcolor">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="dataType" label="标签" width="90">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.dataType === '旧数据' ? 'info' : (scope.row.dataType === '待抢数据' ? 'success' : '')">{{
                    scope.row.dataType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="syskey" label="唯一编号" width="180" v-if="false">
            </el-table-column>
            <el-table-column prop="contractNo" label="合同编号" width="180">
            </el-table-column>
            <el-table-column prop="accountTypeStr" label="合同类型" width="100">
            </el-table-column>
            <el-table-column prop="customerName" label="主借人" width="100">
            </el-table-column>
            <el-table-column prop="provinceName" label="省份" width="100">
            </el-table-column>
            <el-table-column prop="cityName" label="城市" width="100">
            </el-table-column>
            <el-table-column prop="dlrSimpleName" label="专营店简称" width="100">
            </el-table-column>
            <el-table-column prop="businessType" label="模式" width="80">
            </el-table-column>
            <el-table-column prop="totalODDays" label="逾期天数" width="100">
            </el-table-column>
            <el-table-column prop="delinquencyTerm" label="逾期期数" width="100">
            </el-table-column>
            <el-table-column prop="odrentalAmt" label="逾期金额" width="100">
            </el-table-column>
            <el-table-column prop="totalODAmt" label="待催债总额" width="100">
            </el-table-column>
            <el-table-column prop="dcaTypeStr" label="委外类型" width="100">
            </el-table-column>
            <el-table-column prop="relatedContractNum" label="关联合同" width="80">
            </el-table-column>
            <el-table-column prop="loseContactFlagStr" label="逾期原因" width="120">
            </el-table-column>
            <el-table-column prop="customerStatusStr" label="客户状态" width="100">
            </el-table-column>
            <el-table-column prop="writeoffFlagStr" label="是否核销" width="100">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
              <template slot-scope="scope">
                <el-button @click.native.prevent="addPreGrabPool(scope.$index, tableData)"
                  icon="el-icon-circle-plus-outline" type="primary" size="small">
                  添加
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          background :page-sizes="[100, 200, 300, 400]" :page-size="currentPageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </el-main>
    </el-container>
    <el-drawer title="待抢池" :visible.sync="preGrabCasePoolTable" direction="rtl" size="52%">
      <el-button style="margin-left: 10px;margin-bottom: 5px;" v-if="preNumber > 0" type="danger" icon="el-icon-delete"
        @click="clearPool()">清空待抢池</el-button>
      <el-table :data="preGrabCasePoolData" border stripe>
        <el-table-column property="contractNo" label="合同编号" width="200"></el-table-column>
        <el-table-column property="customerName" label="主借人" width="80"></el-table-column>
        <el-table-column property="accountTypeStr" label="合同类型" width="80"></el-table-column>
        <el-table-column property="totalODDays" label="逾期天数" sortable width="120"></el-table-column>
        <el-table-column property="delinquencyTerm" label="逾期期数" width="80"></el-table-column>
        <el-table-column property="odrentalAmt" label="逾期金额" width="100"></el-table-column>
        <el-table-column property="customerStatusStr" label="客户状态" width="120"></el-table-column>
        <el-table-column property="dlrSimpleName" label="专营店简称"></el-table-column>
        <el-table-column fixed="right" label="操作" width="80">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" circle
              @click.native.prevent="removeFromGrabCasePool(scope.$index, preGrabCasePoolData)"> </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
    <el-dialog title="抢案实时监控" :visible.sync="dialogTableVisible">
      <div class="monitor-info">
        <div class="monitor-process">
          <el-progress :percentage="process" :stroke-width="20" :color="customColorMethod"></el-progress>
        </div>
        <div class="monitor-success">
          <el-statistic title="成功占比">
            <template slot="formatter">
              {{ success }} / {{ all }}
            </template>
          </el-statistic>
        </div>
      </div>
      <el-divider></el-divider>
      <div class="case-list">
        <div :class="{
          'case wait': item.status === 0,
          'case success': item.status === 1,
          'case fail': item.status === -1
        }" v-for="item in monitorList" :key="item.contractNo">
          <p class="number">{{ item.tryNumber }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import "@/assets/css/scrollbar.css";
import "@/assets/css/grab.css";
const axios = require("axios");
export default {
  name: "pregrabcase",
  data() {
    return {
      // 最小范围
      d_s: "0",
      // 最大范围
      d_e: "9999",
      // 表格加载
      tableLoading: false,
      // 下载加载
      exportLoading: false,
      // 抽屉控制
      preGrabCasePoolTable: false,
      // 实时抢案监控
      dialogTableVisible: false,
      // 选则的合同类型
      s_accountTypeStrList: [],
      // 选择的客户状态
      s_customerStatusStrList: [],
      // 排除的专营店
      s_excludeDlrSimpleNameList: [],
      // 抢案监控
      monitorList: [],
      // 合同编号
      contractNo: '',
      // 当前页
      currentPage: 1,
      // 页大小
      currentPageSize: 100,
      // 总数
      total: 0,
      // 待抢池总数
      preNumber: 0,
      // 合同类型下拉
      accountTypeStrList: [],
      // 客户状态下拉
      customerStatusStrList: [],
      // 排查专营店下拉
      excludeDlrSimpleNameList: [],
      // 表格数据
      tableData: [],
      // 待抢池数据
      preGrabCasePoolData: [],
      // 表格勾选
      selectedRows: [],
      // 下次执行时间
      nextEightThirty: 0,
      // 监控对象
      monitorInterval: '',
      // 抢案进度
      process: 66,
      success: 0,
      all: 0
    };
  },
  mounted() {
    //关闭页面的丝带
    if (document.getElementsByTagName("canvas")) {
      let arr = document.getElementsByTagName("canvas");
      for (let i = 0; i < arr.length; i++) {
        arr[i].style.display = "none";
      }
    }
    // 初始化检查
    this.checkPwd();
    // 查询下次执行时间
    this.getNextEightThirty();
    // 初始化下拉
    this.accountTypeStrList = this.getGrabCasePreEnum('accountTypeStr');
    this.excludeDlrSimpleNameList = this.getGrabCasePreEnum('dlrSimpleName');
    this.customerStatusStrList = this.getGrabCasePreEnum('customerStatusStr');
    // 初始化查询
    this.getPreCase();
    // 查询待抢池数据
    this.getPreGrabPoolSize();
    // 查询详细数据
    this.getPreGrabPoolInfo();
  },
  computed: {

  },
  methods: {
    mock() {
      this.dialogTableVisible = true;
      this.updateSuccess(21, 30);
    },
    customColorMethod(percentage) {
      if (percentage < 30) {
        return '#909399';
      } else if (percentage < 70) {
        return '#e6a23c';
      } else {
        return '#67c23a';
      }
    },
    handleInput() {
      // 只允许输入正整数
      this.d_e = this.d_e.replace(/[^\d]/g, '');
      this.d_s = this.d_s.replace(/[^\d]/g, '');
    },
    headcolor() {
      return 'head-color';
    },
    // 查询下次抢单时间
    getNextEightThirty() {
      let _this = this;
      axios
        .get("/df/api/getNextStartTime")
        .then((r) => {
          _this.nextEightThirty = r.data.data;
        });
    },
    // 密码检查
    checkPwd() {
      let _this = this;
      let pwd = localStorage.getItem('pwd');
      if (!pwd) {
        _this.$message.error('请重新登录!');
        setTimeout(() => {
          //退回到登录页
          _this.$router.push("/");
        }, 3000);
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPreCase(false);
    },
    handleSizeChange(val) {
      this.currentPageSize = val;
      this.getPreCase(false);
    },
    // 获取下拉枚举
    getGrabCasePreEnum(k) {
      let arr = []
      axios
        .post("/df/api/getGrabCasePreEnum", {
          key: k
        })
        .then((r) => {
          let o = r.data.data;
          o.forEach((e, i) => {
            arr.push({
              label: e,
              value: e,
            })
          })
        });
      return arr;
    },
    // 更新实时进度
    updateSuccess(s, a, p) {
      this.success = s;
      this.all = a;
      this.process = Math.floor(p);
    },
    // 抢案开始
    startGrabCase() {
      let _this = this;
      axios
        .get("/df/api/getGrabMonitorInfo")
        .then((r) => {
          let data = r.data.data;
          if (data.datas.length > 0) {
            // 加载抢案监控信息  
            _this.dialogTableVisible = true;
            _this.monitorList = data.datas;
            _this.updateSuccess(data.success, data.total, data.process);
            _this.monitorInterval = setInterval(() => {
              _this.getMonitor();
            }, 200);
          }
        });
    },
    // 获取监控数据
    getMonitor() {
      let _this = this;
      axios
        .get("/df/api/getGrabMonitorInfo")
        .then((r) => {
          let data = r.data.data;
          if (data.datas.length > 0) {
            _this.monitorList = data.datas;
            _this.updateSuccess(data.success, data.total, data.process);
          } else {
            clearInterval(_this.monitorInterval);
            _this.$message({
              message: '抢案已完成,请收到邮件后查看详细抢案信息!',
              type: 'success'
            });
          }
        });
    },
    // 获取待抢单列表
    async getPreCase(tip, hideLoading) {
      let _this = this;
      let day = []
      day.push(this.d_s)
      day.push(this.d_e)
      if (!hideLoading) this.tableLoading = true;
      await axios
        .post("/df/api/getGrabCasePre", {
          accountTypeStrList: _this.s_accountTypeStrList,
          totalODDaysArray: day,
          contractNo: _this.contractNo,
          customerStatusStrList: _this.s_customerStatusStrList,
          excludeDlrSimpleNameList: _this.s_excludeDlrSimpleNameList,
          pageNum: _this.currentPage,
          pageSize: _this.currentPageSize
        })
        .then(function (response) {
          let r = response.data;
          if (r.code == 0) {
            if (tip) {
              _this.$message({
                message: '查询成功!',
                type: 'success'
              });
            }
            _this.tableData = r.data;
            _this.total = r.rowcount;
          } else {
            _this.$message.error('查询异常:' + r.msg);
          }
          if (!hideLoading) _this.tableLoading = false;
        });
    },
    // 添加到待抢池
    async addPreGrabPool(i, d) {
      let _this = this;
      let data = d[i];
      data.grabType = '人工';
      await axios
        .post("/df/api/addGrabCasePool", [data])
        .then(function (response) {
          let r = response.data;
          if (r.code == 0) {
            _this.$message({
              message: '添加成功!',
              type: 'success'
            });
          } else {
            _this.$message.error('添加失败:' + r.msg);
          }
          _this.getPreGrabPoolSize();
          // 查询详细数据
          _this.getPreGrabPoolInfo();
          // 重新查询
          _this.getPreCase(false, true);
        });
    },
    // 添加勾选到待抢池
    async addPreGrabPoolBatch() {
      let _this = this;
      // 获取当前选中的行数据
      this.selectedRows = this.$refs.multipleTable.selection;
      let arr = [];
      if (this.selectedRows.length == 0) {
        _this.$message({
          type: 'error',
          message: '请先勾选需要添加的数据!'
        });
        return;
      }
      this.selectedRows.forEach((e, i) => {
        e.grabType = '人工';
        arr.push(e);
      });
      await axios
        .post("/df/api/addGrabCasePool", arr)
        .then(function (response) {
          let r = response.data;
          if (r.code == 0) {
            _this.$message({
              message: '批量添加成功!',
              type: 'success'
            });
          } else {
            _this.$message.error('添加失败:' + r.msg);
          }
          _this.getPreGrabPoolSize();
          // 查询详细数据
          _this.getPreGrabPoolInfo();
          // 重新查询
          _this.getPreCase(false);
        });
    },
    // 清空待抢池
    clearPool() {
      let _this = this;
      _this.$confirm('确认删除全部待抢池数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios
          .post("/df/api/clearGrabCasePool", {})
          .then(function (response) {
            let r = response.data;
            if (r.data) {
              _this.$message({
                type: 'success',
                message: '清除成功!'
              });
            } else {
              _this.$message({
                type: 'error',
                message: '清除失败!'
              });
            }
            _this.getPreGrabPoolSize();
            // 查询详细数据
            _this.getPreGrabPoolInfo();
            // 重新查询
            _this.getPreCase(false);
          });
      }).catch(() => {
        _this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });

    },
    // 移除待选池数据
    async removeFromGrabCasePool(i, d) {
      let _this = this;
      let data = d[i];
      data.grabType = '人工';
      await axios
        .post("/df/api/removeFromGrabCasePool", [data])
        .then(function (response) {
          let r = response.data;
          if (r.code == 0) {
            _this.$message({
              message: '已删除!',
              type: 'success'
            });
          } else {
            _this.$message.error('删除失败:' + r.msg);
          }
          // 更新总数
          _this.getPreGrabPoolSize();
          // 查询详细数据
          _this.getPreGrabPoolInfo();
          // 重新查询
          _this.getPreCase(false);
        });
    },
    // 下载待抢清单
    exportPreCase() {
      let _this = this;
      let day = []
      day.push(this.d_s)
      day.push(this.d_e)
      _this.exportLoading = true;
      axios(
        {
          url: '/df/api/exportGrabCasePre',
          method: 'POST',
          data: {
            accountTypeStrList: _this.s_accountTypeStrList,
            totalODDaysArray: day,
            contractNo: _this.contractNo,
            customerStatusStrList: _this.s_customerStatusStrList,
            excludeDlrSimpleNameList: _this.s_excludeDlrSimpleNameList,
            pageNum: _this.currentPage,
            pageSize: _this.currentPageSize
          },
          responseType: 'blob',
        }
      ).then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        let d = Date.now();
        link.setAttribute('download', `导出-${d}.xlsx`);
        document.body.appendChild(link);
        link.click();
        _this.exportLoading = false;
      });
    },
    // 导入待抢清单
    importGrabCasePoolSuccess(r) {
      this.$message({
        message: '导入成功!',
        type: 'success'
      });
      this.getPreGrabPoolSize();
      // 查询详细数据
      this.getPreGrabPoolInfo();
      // 重新查询
      this.getPreCase(false);
    },
    // 查询待抢池数据量
    getPreGrabPoolSize() {
      let _this = this;
      axios
        .get("/df/api/getGrabCasePoolSize", {})
        .then(function (response) {
          let r = response.data;
          _this.preNumber = r.data;
        });
    },
    // 查询待抢池详细信息
    getPreGrabPoolInfo() {
      let _this = this;
      axios
        .get("/df/api/getGrabCasePool", {})
        .then(function (response) {
          let r = response.data;
          _this.preGrabCasePoolData = r.data;
        });
    },
    //退出系统
    async exit() {
      let _this = this;
      await this.$confirm("即将退出系统, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //退回到登录页
          _this.$router.push("/");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出",
          });
        });
    },
  },
};
</script>
